<template>
   <el-button @click="handleAdd" v-if="$filters.auth($filters.PrivilegeType.Add)" class="button-header"  type="primary" :icon="Plus">添加城市</el-button>
   <el-form inline :model="query" class="filter" label-width="100px">
    <el-form-item label="城市名称：">
      <el-col :span="22">
        <el-input v-model="query.name" placeholder="请输入城市名称" />
      </el-col>
    </el-form-item>
    <el-form-item class="filter-actions">
      <el-button class="button-small" type="primary" @click="handleSearch">筛选</el-button>
      <el-button type="text" class="button-reset" @click="handleClear">重置筛选条件</el-button>
    </el-form-item> 
   </el-form>
   <grid url="opencity/list" :params="query" orderbyName='Sequence' ref="datalist">
      <el-table-column prop="name" label="城市名称" width="120" />
      <el-table-column prop="firstLetter" label="商业圈" min-width="500" >
        <template #default="scope" > 
          <el-tag class="ml-10" v-for="(item,key,index) in scope.row.business" :key='index' closable  @close="handleListbusinessDelete(key)">{{item}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="热门" sortable prop="sequence" width="80">
        <template #default="scope">
          <el-switch v-model="scope.row.hot" @change="changeHot(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="right" width="150"  v-if="$filters.auth($filters.PrivilegeType.Edit) || $filters.auth($filters.PrivilegeType.Delete)">
      <template #default="scope">
        <el-button type="text" v-if="$filters.auth($filters.PrivilegeType.Edit)" @click="handleEdit(scope.row.regionId)">编辑</el-button>
        <el-popconfirm :width="300" v-if="$filters.auth($filters.PrivilegeType.Delete)" class="btn-popconfirm" @confirm="handleDelete(scope.row.regionId)" confirmButtonText="确认" cancelButtonText="取消" title="确定要删除该员工吗？">
          <template #reference>
            <el-button type="text" size="small">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
    </grid>
   <el-dialog append-to-body v-model="postForm.dialogVisible" :title="postForm.title" width="700px">
    <el-form ref="postFormRef" label-width="150px"  :model="postForm.form" :rules="postForm.rules">
      <el-form-item label="设施名称：" prop="regionId">
        <region v-model="postForm.form.regionId" :level="1" @text="addressText = $event" />
      </el-form-item>
      <el-form-item label="商业圈：">
        <el-table :data="postForm.form.business" style="width: 100%">
          <el-table-column label="商业圈名称">
            <template #default="scope">
              <form-item :prop="'form.business.' + scope.$index + '.name'"  :rules="[{ required: true, message: '请输入品牌名称', trigger: 'blur' }]" >
                <el-input v-model="scope.row.name" :key="scope.$index" placeholder="请输入名称" clearable />
              </form-item>
            </template>
          </el-table-column>
          <el-table-column label="排序" sortable prop="sequence">
            <template #default="scope">
              <el-input-number v-model="scope.row.sequence" controls-position="right"  :min="0" :max="99999999" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="right" width="100">
            <template #default="scope">
              <el-button @click="handleBusinessDelete(scope.$index)" type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
          <el-button @click="handleBusinessAdd"  class="button-header"  type="primary" :icon="Plus">添加商圈</el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="postForm.dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave(postFormRef)">确定</el-button>
      </span>
    </template>
   </el-dialog>
</template>
<script lang="ts" setup>
import {ref,watch} from 'vue'
import Grid from '@/components/Grid.vue'
import {Plus} from '@element-plus/icons-vue'
import {ElForm, ElMessage, ElMessageBox} from 'element-plus'
import {OpenCitySave, OpenCityDelete,GetOpenCityDetails,UpdateOpenCitySequence,businessDelete,UpdateOpenCityHot} from '@/api/openCity'
import Region from  '@/components/Region.vue'
const query = ref<OpenCityQuery>({
  name:''
})
const addressText = ref<string>('')

const validRegion = (rule: any, value: any, callback: any) => {
  if(postForm.value.form.regionId === 0) {
    return callback(new Error('请选择城市'))
  }
  callback()
}


const postForm = ref<DialogForm<OpenCity>>({
 title:'添加城市',
 dialogVisible: false,
 form: {
  regionId: 0,
  sequence: 0,
  business: [],
  isEdit: false,
  firstLetter: '',
  hot: false
 },
  rules:{
    regionId: [{ required: true,validator: validRegion, trigger: 'change' }],
  }
})


const datalist = ref<InstanceType<typeof Grid>>()
type FormInstance = InstanceType<typeof ElForm>
const postFormRef = ref<FormInstance>()
/**
 * 添加城市
 */
const handleAdd = ():void => {
  postForm.value.form =  {
    regionId: 0,
    sequence: 0,
    business: [],
    isEdit: false,
    firstLetter: '',
    hot: false
  }
  postForm.value.dialogVisible = true
  postForm.value.title ='添加城市'
}
/**
 * 编辑城市
 */
const handleEdit = (regionId: number):void => {
  GetOpenCityDetails(regionId).then((res:ServiceResponse<OpenCity>) => {
     if(res.success && res.data )
        postForm.value.form = res.data 
      postForm.value.form.isEdit = true
      postForm.value.dialogVisible = true
      postForm.value.title ='编辑城市'
  })
}
/**
 * 编辑序号
 * @param row 
 */
const handleChangeSequence = (row:Brand):void => {
  UpdateOpenCitySequence(row.id,row.sequence).then((res:ServiceResponse<any>) => {
    if(res.success) {
          ElMessage.success('保存成功')
          datalist.value?.loadData()
        } else  ElMessage.error(res.msg)
  })
}
/**
 * 点击确定
 * @param formEl 
 */
const handleSave = (formEl: FormInstance | undefined): void => {
  if (!formEl) return
  formEl.validate((valid) => {
    if(valid) {
      try {
        postForm.value.form.business.forEach((item:BusinessCircle,index:number) => {
            if(!item.name) throw new Error(`请输入商业圈名称`)
        })
      }
      catch(e) {
        console.log(e)
      }
      OpenCitySave(postForm.value.form).then((res:ServiceResponse<any>) => {
        if(res.success) {
          ElMessage.success('保存成功')
          datalist.value?.loadData()
          postForm.value.dialogVisible = false
        } else  ElMessage.error(res.msg)
      })
    }
  })
}
/**
 * 删除
 * @param id 
 */
const handleDelete = (regionId:number):void => {
  OpenCityDelete(regionId).then(((res:ServiceResponse<any>) => {
    if(res.success) {
          ElMessage.success('删除成功')
          datalist.value?.loadData()
        } else  ElMessage.error(res.msg)
  }))
}
/**
 * 热门
 * @param row 
 */
const changeHot = (row:OpenCityView) => {
  UpdateOpenCityHot(row.regionId,row.hot).then((res:ServiceResponse<any>) => {
    if(res.success) {
          ElMessage.success('保存成功')
          datalist.value?.loadData()
        } else  ElMessage.error(res.msg)
  })
}
 /**
  * 添加商业圈
  */
const handleBusinessAdd = ():void => {
  postForm.value.form.business.push({
    name:'',
    id: 0,
    cityRegionId: 0,
    sequence: 0
  })
}
/**
 * 删除商业圈
 * @param index 
 */
const handleBusinessDelete = (index: number): void => {
    ElMessageBox.confirm('确定要删除吗?', '删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      postForm.value.form.business.splice(index, 1)
    }).catch(() => {})
}

const handleListbusinessDelete = (id: number): void => {
    ElMessageBox.confirm('确定要删除吗?', '删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      businessDelete(id).then((res:ServiceResponse<any>)=> {
        if(res.success) {
          ElMessage.success('删除成功')
          datalist.value?.loadData()
        }
        else
          ElMessage.error(res.msg)
      })
    }).catch(() => {})
}
const handleSearch = ():void => {
  datalist.value?.loadData()
}
const handleClear = ():void => {
  query.value.name = ''
  datalist.value?.loadData()
}
</script>
<style lang="scss" scoped>
@import "@/assets/styles/mixin.scss";
@import "@/assets/styles/tablePage.scss";
.ml-10 {
  margin-left: 10px;
}
</style>